package com.modulemanager.models

import android.net.Uri
import com.libbase.extension.getQueryItems
import com.libbase.utils.MapUtils

data class BuildModel(
    val host: String?,
    val moduleType: String,
    val moduleId: String?,
    val type: String?,
    val id: String?,
    val params: Map<String, Any>?,
    val hash: String?
) {
    companion object {
        fun build(url: String, params: Map<String, Any>?): BuildModel? {
            return build(Uri.parse(url), params)
        }

        fun build(uri: Uri, params: Map<String, Any>?): BuildModel? {
            if (uri.pathSegments.size <= 0) {
                return null
            }

            var mergedParams: Map<String, Any>? = MapUtils.merging(uri.getQueryItems(), params)

            val moduleType: String = uri.pathSegments[0]
            val pageType: String? = when (uri.pathSegments.size) {
                1 -> {
                    null
                }
                else -> {
                    uri.pathSegments[1]
                }
            }

            if (uri.pathSegments.size > 2) {
                mergedParams = MapUtils.merging(mergedParams, mapOf("pathParams" to uri.pathSegments.drop(2)))
            }

            val moduleId: String?
            val pageId: String?
            if (mergedParams != null) {
                moduleId = mergedParams["moduleId"] as? String
                pageId = mergedParams["pageId"] as? String ?: mergedParams["id"] as? String
            } else {
                moduleId = null
                pageId = null
            }

            return BuildModel(
                uri.host,
                moduleType,
                moduleId,
                pageType,
                pageId,
                mergedParams,
                uri.fragment
            )
        }

        fun url(
            moduleType: String, moduleId: String?,
            pageType: String, pageId: String?
        ): String {
            var url = "app://page/${moduleType}/${pageType}"

            var params = ""
            moduleId?.let {
                params += "moduleId=${it}"
            }

            pageId?.let {
                if (params.isNotEmpty()) {
                    params += "&"
                }
                params += "pageId=${it}"
            }

            if (params.isNotEmpty()) {
                url += "?$params"
            }

            return url
        }
    }
}